package com.zzyk.main.configuration.aspectj;

import com.zzyk.main.configuration.exception.UserException;

import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

@Aspect
@Component
@EnableAsync
public class UserAspect {
    @Autowired
    private ISysUserService sysUserService;

    @Pointcut("execution(public * com.zzyk.*.controller.SysUserController.saveUser(..))")
    public void userSavePoint() {
    }

    @Pointcut("execution(public * com.zzyk.*.controller.SysUserController.deleteUser(..))")
    public void userDelPoint() {
    }

    @Before("userSavePoint()")
    public void beforeSaveUser(JoinPoint joinPoint) throws UserException {
        if (joinPoint.getArgs() != null && joinPoint.getArgs()[0] != null && joinPoint.getArgs()[0] instanceof SysUser) {
            SysUser user = (SysUser) joinPoint.getArgs()[0];
            if (user.getId() != null) {
                SysUser sysUser = sysUserService.getUser(user.getId());
                if (sysUser.getReadonly() == 1) {
                    throw new UserException("禁止修改内置用户");
                }
            }
        }
    }

    @Before("userDelPoint()")
    public void beforeDelUser(JoinPoint joinPoint) throws UserException {
        if (joinPoint.getArgs() != null && joinPoint.getArgs()[0] != null) {
            Integer id = (Integer) joinPoint.getArgs()[0];
            SysUser sysUser = sysUserService.getUser(id);
            SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            if (sysUser == null) {
                throw new UserException("用户不存在");
            } else if (sysUser.getReadonly() == 1) {
                throw new UserException("禁止删除内置用户");
            } else if (id.equals(currentUser.getId())) {
                throw new UserException("不能删除自己");
            }
        }
    }
}
